<template>
	<view class="container">
		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-input">
				<image class="search-icon" src="/static/icons/search.png"></image>
				<input type="text" v-model="searchKey" placeholder="搜索发展对象姓名" @input="handleSearch" />
			</view>
		</view>
		
		<!-- 发展对象列表 -->
		<view class="contact-list">
			<view v-for="(member, index) in filteredMembers" :key="index" 
				class="contact-item" 
				:class="{ 
					'selected': selectedMember === member.id,
					'disabled': !canSelectMember(member.id)
				}"
				:style="{ animationDelay: index * 0.1 + 's' }"
				@click="selectMember(member)">
				<view class="contact-info">
					<image class="avatar" :src="member.avatarUrl || '/static/images/default-avatar.png'" mode="aspectFill"></image>
					<view class="info-content">
						<view class="name-row">
							<text class="name">{{member.name}}</text>
							<text class="role">发展对象</text>
							<text v-if="memberContacts[member.id] > 0" class="contact-count">
								已有{{memberContacts[member.id].length}}名入党介绍人
							</text>
						</view>
						<view class="detail-row">
							<text class="detail">{{member.phone}}</text>
						</view>
					</view>
				</view>
				<view class="select-indicator">
					<view class="check-circle" :class="{ 
						'checked': selectedMember === member.id,
						'disabled': !canSelectMember(member.id)
					}">
						<text class="check-icon" v-if="selectedMember === member.id">✓</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view v-if="filteredMembers.length === 0" class="empty-state">
			<image class="empty-icon" src="/static/icons/empty.png"></image>
			<text class="empty-text">暂无发展对象</text>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-button" v-if="filteredMembers.length > 0">
			<button class="submit-btn" @click="showContactSelector">
				选择入党介绍人
			</button>
		</view>
		
		<!-- 入党介绍人选择弹窗 -->
		<uni-popup ref="contactPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">选择入党介绍人</text>
					<text class="close-btn" @click="closeContactPopup">×</text>
				</view>
				
				<!-- 当前入党介绍人 -->
				<view class="current-contacts" v-if="currentContacts.length > 0">
					<view class="section-title">当前入党介绍人</view>
					<view class="contact-list">
						<view v-for="(contact, index) in currentContacts" :key="index" 
							class="contact-item current">
							<view class="contact-info">
								<image class="avatar" :src="contact.avatarUrl || '/static/images/default-avatar.png'" mode="aspectFill"></image>
								<view class="info-content">
									<view class="name-row">
										<text class="name">{{contact.name}}</text>
										<text class="role">正式党员</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<view class="section-title">选择新的入党介绍人（最多两名）</view>
				<scroll-view class="contact-selector" scroll-y>
					<view v-for="(contact, index) in contacts" :key="index" 
						class="contact-option"
						:class="{ 'selected': selectedContacts.some(item => item.id === contact.id) }"
						@click="selectContact(contact)">
						<view class="contact-info">
							<image class="avatar" :src="contact.avatarUrl || '/static/images/default-avatar.png'" mode="aspectFill"></image>
							<view class="info-content">
								<view class="name-row">
									<text class="name">{{contact.name}}</text>
									<text class="role">正式党员</text>
								</view>
							</view>
						</view>
						<view class="select-indicator">
							<view class="check-circle" :class="{ 'checked': selectedContacts.some(item => item.id === contact.id) }">
								<text class="check-icon" v-if="selectedContacts.some(item => item.id === contact.id)">✓</text>
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="popup-footer">
					<button class="confirm-btn" :disabled="selectedContacts.length === 0" @click="handleSubmit">
						确认指定 (已选{{selectedContacts.length}}名)
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { sumbitintroduceUser,getDeptUsers, sumbitContactUsers, contactGetUser, userGetContact,userInfoAsync, deleteContactUsers, introduceGetUser, deleteIntroduceUsers, userGetintroduce } from '@/common/js/api.js';

const userId = uni.getStorageSync('userId');
const members = ref([]); // 发展对象列表
const contacts = ref([]); // 正式党员列表
const searchKey = ref('');
const selectedMember = ref(null); // 选中的发展对象
const selectedContact = ref(null); // 选中的入党介绍人
const selectedContacts = ref([]); // 多选的入党介绍人列表
const isLoading = ref(false);
const contactPopup = ref(null);
const memberContacts = ref({}); // 存储每个发展对象的入党介绍人信息
const currentContacts = ref([]); // 当前选中发展对象的入党介绍人

// 过滤后的发展对象列表
const filteredMembers = computed(() => {
	if (!searchKey.value) return members.value;
	return members.value.filter(member => 
		member.name.toLowerCase().includes(searchKey.value.toLowerCase())
	);
});

// 获取支部成员列表
const fetchMembers = async () => {
	try {
		isLoading.value = true;
		const res = await getDeptUsers(userId);
		if (res.code === 200) {
			// 过滤出发展对象
			members.value = res.data.sameDeptPeople.filter(person => 
				person.politicalStatus === '发展对象'
			);
			// 过滤出正式党员
			contacts.value = res.data.sameDeptPeople.filter(person => 
				person.politicalStatus === '正式党员'
			);
			
			// 获取每个发展对象的入党介绍人信息
			for (const member of members.value) {
				try {
					const contactRes = await userGetintroduce(member.id);
					if (contactRes.code === 200) {
						memberContacts.value[member.id] = contactRes.data;
					}
				} catch (error) {
					console.error('获取入党介绍人信息失败:', error);
					memberContacts.value[member.id] = [];
				}
			}
		} else {
			uni.showToast({
				title: '获取成员列表失败',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('获取成员列表失败:', error);
		uni.showToast({
			title: '获取成员列表失败',
			icon: 'none'
		});
	} finally {
		isLoading.value = false;
	}
};

// 检查发展对象是否可以选择
const canSelectMember = (memberId) => {
	return true;
};

// 处理搜索
const handleSearch = () => {
	// 搜索逻辑已通过计算属性实现
};

// 选择发展对象
const selectMember = (member) => {
	if (!canSelectMember(member.id)) {
		uni.showToast({
			title: '该发展对象已有两名入党介绍人',
			icon: 'none'
		});
		return;
	}
	selectedMember.value = member.id;
	console.log('选中的发展对象ID:', selectedMember.value);
};

// 显示入党介绍人选择器
const showContactSelector = async() => {
	
	if (!selectedMember.value) {
		uni.showToast({
			title: '请先选择发展对象',
			icon: 'none'
		});
		return;
	}
	// 获取当前选中发展对象的入党介绍人
	for (var i = 0;i < memberContacts.value[selectedMember.value].length;++i){
		console.log('hello world');
		const res = await userInfoAsync(memberContacts.value[selectedMember.value][i]);
		const contact = res.data.user;
		currentContacts.value.push(contact);
	}
	contactPopup.value.open();
};

// 关闭入党介绍人选择器
const closeContactPopup = () => {
	contactPopup.value.close();
	selectedContacts.value = [];
	currentContacts.value = [];
};

// 选择入党介绍人
const selectContact = (contact) => {
	const index = selectedContacts.value.findIndex(item => item.id === contact.id);
	if (index > -1) {
		// 如果已经选中，则取消选中
		selectedContacts.value.splice(index, 1);
	} else {
		// 如果未选中，则添加到选中列表
		if (selectedContacts.value.length >= 2) {
			uni.showToast({
				title: '最多只能选择两名入党介绍人',
				icon: 'none'
			});
			return;
		}
		selectedContacts.value.push(contact);
	}
};

// 提交选择
const handleSubmit = async () => {
	if (selectedContacts.value.length === 0) {
		uni.showToast({
			title: '请选择入党介绍人',
			icon: 'none'
		});
		return;
	}
	
	try {
		isLoading.value = true;
		
		// 删除原有的入党介绍人
		for (var i = 0; i < memberContacts.value[selectedMember.value].length; ++i) {
			const res = await deleteIntroduceUsers(memberContacts.value[selectedMember.value][i], selectedMember.value);
		} 
		
		// 添加新的入党介绍人
		for (const contact of selectedContacts.value) {
			const res = await sumbitintroduceUser({
				userId: selectedMember.value,
				introducerId: contact.id
			});
		}
		
		uni.showToast({
			title: '指定成功',
			icon: 'success',
			duration: 1500,
			success: () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		});
	} catch (error) {
		uni.showToast({
			title: '指定失败',
			icon: 'none'
		});
		console.log(error);
	} finally {
		isLoading.value = false;
	}
};

onMounted(() => {
	fetchMembers();
});
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background: linear-gradient(135deg, #f6f8fc 0%, #f1f4f9 100%);
	padding: 20rpx;
	padding-bottom: 120rpx;
}

.search-box {
	padding: 20rpx;
	background: rgba(255, 255, 255, 0.9);
	backdrop-filter: blur(10px);
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;
	
	&:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.12);
	}
	
	.search-input {
		display: flex;
		align-items: center;
		background: rgba(245, 245, 245, 0.8);
		border-radius: 40rpx;
		padding: 20rpx 30rpx;
		transition: all 0.3s ease;
		
		&:focus-within {
			background: #fff;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		}
		
		.search-icon {
			width: 36rpx;
			height: 36rpx;
			margin-right: 20rpx;
			opacity: 0.6;
		}
		
		input {
			flex: 1;
			font-size: 28rpx;
			color: #333;
			
			&::placeholder {
				color: #999;
			}
		}
	}
}

.contact-list {
	.contact-item {
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(10px);
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		transform: translateY(0);
		transition: all 0.3s ease;
		animation: slideIn 0.5s ease forwards;
		opacity: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		&:hover {
			transform: translateY(-4rpx);
			box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.12);
		}
		
		&.selected {
			background: rgba(255, 122, 69, 0.05);
			border: 2rpx solid rgba(255, 122, 69, 0.2);
		}
		
		&.disabled {
			opacity: 0.6;
			cursor: not-allowed;
			
			&:hover {
				transform: none;
				box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
			}
		}
		
		.contact-info {
			display: flex;
			align-items: center;
			flex: 1;
			
			.avatar {
				width: 120rpx;
				height: 120rpx;
				border-radius: 60rpx;
				margin-right: 30rpx;
				border: 4rpx solid #fff;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
				transition: all 0.3s ease;
				
				&:hover {
					transform: scale(1.05);
				}
			}
			
			.info-content {
				flex: 1;
				
				.name-row {
					display: flex;
					align-items: center;
					margin-bottom: 16rpx;
					
					.name {
						font-size: 36rpx;
						font-weight: 600;
						color: #333;
						margin-right: 20rpx;
					}
					
					.role {
						font-size: 24rpx;
						padding: 6rpx 20rpx;
						border-radius: 30rpx;
						background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
						color: #fff;
						font-weight: 500;
					}
					
					.contact-count {
						font-size: 24rpx;
						color: #ff7a45;
						margin-left: 20rpx;
						padding: 4rpx 16rpx;
						background: rgba(255, 122, 69, 0.1);
						border-radius: 20rpx;
					}
				}
				
				.detail-row {
					display: flex;
					align-items: center;
					
					.detail {
						font-size: 28rpx;
						color: #666;
						margin-right: 30rpx;
						display: flex;
						align-items: center;
						
						&::before {
							content: '';
							display: inline-block;
							width: 8rpx;
							height: 8rpx;
							background: #999;
							border-radius: 50%;
							margin-right: 12rpx;
						}
					}
				}
			}
		}
		
		.select-indicator {
			margin-left: 20rpx;
			
			.check-circle {
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				border: 2rpx solid #ddd;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.3s ease;
				
				&.checked {
					background: #ff7a45;
					border-color: #ff7a45;
					
					.check-icon {
						color: #fff;
						font-size: 24rpx;
					}
				}
				
				&.disabled {
					background: #f5f5f5;
					border-color: #ddd;
					cursor: not-allowed;
				}
			}
		}
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 0;
	animation: fadeIn 0.5s ease;
	
	.empty-icon {
		width: 240rpx;
		height: 240rpx;
		margin-bottom: 40rpx;
		opacity: 0.8;
	}
	
	.empty-text {
		font-size: 32rpx;
		color: #999;
		font-weight: 500;
	}
}

.bottom-button {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 40rpx;
	background: rgba(255, 255, 255, 0.9);
	backdrop-filter: blur(10px);
	box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
	
	.submit-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background: linear-gradient(135deg, #ff7a45 0%, #ff9a6c 100%);
		color: #fff;
		font-size: 32rpx;
		font-weight: 500;
		border-radius: 40rpx;
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(0.98);
		}
		
		&:disabled {
			background: #ccc;
			opacity: 0.8;
		}
	}
}

@keyframes slideIn {
	from {
		opacity: 0;
		transform: translateY(20rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

// 添加弹窗相关样式
.popup-content {
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	padding: 30rpx;
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		
		.popup-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}
		
		.close-btn {
			font-size: 40rpx;
			color: #999;
			padding: 10rpx;
		}
	}
	
	.section-title {
		font-size: 28rpx;
		color: #666;
		margin: 20rpx 0;
		padding: 0 20rpx;
	}
	
	.current-contacts {
		padding: 20rpx;
		background: #f8f8f8;
		border-radius: 12rpx;
		margin: 20rpx;
		
		.contact-list {
			.contact-item {
				background: #fff;
				border-radius: 12rpx;
				padding: 20rpx;
				margin-bottom: 20rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				&.current {
					border: 2rpx solid #ff7a45;
					background: rgba(255, 122, 69, 0.05);
				}
				
				.contact-info {
					display: flex;
					align-items: center;
					
					.avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 40rpx;
						margin-right: 20rpx;
					}
					
					.info-content {
						.name-row {
							display: flex;
							align-items: center;
							
							.name {
								font-size: 28rpx;
								color: #333;
								margin-right: 16rpx;
							}
							
							.role {
								font-size: 22rpx;
								padding: 4rpx 16rpx;
								border-radius: 24rpx;
								background: linear-gradient(135deg, #ff7a45 0%, #ff9a6c 100%);
								color: #fff;
							}
						}
					}
				}
			}
		}
	}
	
	.contact-selector {
		max-height: 400rpx;
		
		.contact-option {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx;
			border-bottom: 2rpx solid #f5f5f5;
			
			&:last-child {
				border-bottom: none;
			}
			
			&.selected {
				background: rgba(255, 122, 69, 0.05);
				border: 2rpx solid rgba(255, 122, 69, 0.2);
			}
			
			.contact-info {
				display: flex;
				align-items: center;
				
				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 40rpx;
					margin-right: 20rpx;
				}
				
				.info-content {
					.name-row {
						display: flex;
						align-items: center;
						
						.name {
							font-size: 28rpx;
							color: #333;
							margin-right: 16rpx;
						}
						
						.role {
							font-size: 22rpx;
							padding: 4rpx 16rpx;
							border-radius: 24rpx;
							background: linear-gradient(135deg, #ff7a45 0%, #ff9a6c 100%);
							color: #fff;
						}
					}
				}
			}
		}
	}
	
	.popup-footer {
		margin-top: 30rpx;
		padding-top: 20rpx;
		border-top: 2rpx solid #f5f5f5;
		
		.confirm-btn {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			background: linear-gradient(135deg, #ff7a45 0%, #ff9a6c 100%);
			color: #fff;
			font-size: 32rpx;
			font-weight: 500;
			border-radius: 40rpx;
			
			&:disabled {
				background: #ccc;
				opacity: 0.8;
			}
		}
	}
}
</style> 